package com.yuyou.fn.crm.service.impl;

import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.crm.entity.FromCategory;
import com.yuyou.fn.crm.mapper.FromCategoryMapper;
import com.yuyou.fn.crm.service.IFromCategoryService;
import com.yuyou.fn.crm.vo.FromCategoryRelativeVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 *
 * FromCategory 表数据服务层接口实现类
 *
 */
@Service
public class FromCategoryServiceImpl extends SuperServiceImpl<FromCategoryMapper, FromCategory,Long> implements IFromCategoryService {


    @Override
    public List<FromCategory> findAllFromCategoryByAreaTeamId(Long areaTeamId) {
        Example<FromCategory> example = FromCategory.createExample();
        example.orderBy("createTime").desc();
        example.createCriteria().andEqualTo("areaTeamId" , areaTeamId );
        return findListByExample(example);
    }

    @Override
    public List<FromCategory> findRootFromCategoryByAreaTeamId(Long areaTeamId) {
        Example<FromCategory> example = FromCategory.createExample();
        example.orderBy("createTime").desc();
        example.createCriteria().andEqualTo("areaTeamId" , areaTeamId ).andEqualTo("parentCategoryId" , 0l );
        return findListByExample(example);
    }

    @Override
    public List<FromCategory> findSubFromCategoryByRootFromCategoryId(Long rootFromCategoryId) {
        Example<FromCategory> example = FromCategory.createExample();
        example.orderBy("createTime").desc();
        example.createCriteria().andEqualTo("parentCategoryId" , rootFromCategoryId );
        return findListByExample(example);
    }

    @Override
    public void saveOrUpdateBigFromCategory(Long categoryId, Long areaTeamId, String categoryName) {
        if(categoryId == null ){
            createFromCategory(areaTeamId,categoryName,0l);
        }else{
            updateFromCategory(categoryId,areaTeamId,categoryName,0l);
        }
    }

    @Override
    @Transactional
    public void saveOrUpdateSmallFromCategory(Long parentFromCategoryId, List<String> categoryNames) {
        FromCategory root = findById(parentFromCategoryId);
        if(root == null ){
            throw new BusException("所属的父级不存在");
        }

        delCategory(parentFromCategoryId);

        if(categoryNames == null || categoryNames.size() == 0 ){
            return ;
        }

        List<FromCategory> fromCategories = new ArrayList<>(categoryNames.size());
        for(String name : categoryNames ){
            //validName(name);
            FromCategory fromCategory = new FromCategory();
            fromCategory.setAreaTeamId(root.getAreaTeamId());
            fromCategory.setCategoryName(name);
            fromCategory.setUpdateTime(TimeUtils.now());
            fromCategory.setCreateTime(TimeUtils.now());
            fromCategory.setParentCategoryId(parentFromCategoryId);
            fromCategories.add(fromCategory);
        }

        try{
            insertBatch(fromCategories);
        }catch (Exception e){
            if(e.getMessage().contains("Duplicate entry")){
                throw new BusException("名称不能重复");
            }else{
                throw new BusException("保存失败",e);
            }
        }



    }

    private void delCategory(Long parentFromCategoryId) {
        Example<FromCategory> fromCategoryExample = FromCategory.createExample();
        fromCategoryExample.createCriteria().andEqualTo("parentCategoryId" , parentFromCategoryId );
        deleteByExample(fromCategoryExample);
    }

    @Override
    @Transactional
    public void delBigFromCategory(Long categoryId) {
        deleteById(categoryId);
        delCategory(categoryId);

    }

    @Override
    public List<FromCategoryRelativeVo> findFromCategoryRelative(long areaTeamId) {
        List<FromCategory> fromCategories = this.findAllFromCategoryByAreaTeamId(areaTeamId);
        Map<Long, List<FromCategory>> fromCategoryMap = BeanUtils.toGroup(fromCategories, "parentCategoryId");
        List<FromCategory> parentList=fromCategoryMap.get(0l);
        if (!Utils.isEmpty(parentList)){
            List<FromCategoryRelativeVo> list=new ArrayList<>(parentList.size());
            for (FromCategory fromCategory:fromCategories){
                FromCategoryRelativeVo fromCategoryRelativeVo=new FromCategoryRelativeVo();
                fromCategoryRelativeVo.setParentFromCategory(fromCategory);
                fromCategoryRelativeVo.setChildFromCategories(fromCategoryMap.get(fromCategory.getCategoryId()));
                list.add(fromCategoryRelativeVo);
            }
            return list;
        }


        return Collections.EMPTY_LIST;
    }

    private void createFromCategory(Long areaTeamId, String categoryName, Long parentFromCategoryId){
        //validName(categoryName);
        FromCategory fromCategory = new FromCategory();
        fromCategory.setAreaTeamId(areaTeamId);
        fromCategory.setCategoryName(categoryName);
        fromCategory.setUpdateTime(TimeUtils.now());
        fromCategory.setCreateTime(TimeUtils.now());
        fromCategory.setParentCategoryId(parentFromCategoryId);
        try{
            insertSelective(fromCategory);
        }catch (Exception e){
            if(e.getMessage().contains("Duplicate entry")){
                throw new BusException("名称不能重复");
            }else{
                throw new BusException("保存失败",e);
            }
        }
    }

    private void updateFromCategory(Long categoryId, Long areaTeamId, String categoryName,Long parentFromCategoryId){
        FromCategory fromCategory = new FromCategory();
        fromCategory.setCategoryId(categoryId);
        fromCategory.setAreaTeamId(areaTeamId);
        fromCategory.setCategoryName(categoryName);
        fromCategory.setUpdateTime(TimeUtils.now());
        fromCategory.setParentCategoryId(parentFromCategoryId);
        try{
            updateSelectiveById(fromCategory);
        }catch (Exception e){
            if(e.getMessage().contains("Duplicate entry")){
                throw new BusException("名称不能重复");
            }else{
                throw new BusException("保存失败",e);
            }
        }

    }

    private final static Pattern chinese = Pattern.compile("[\u4E00-\u9FA5]*");

    private void validName(String name ){
        if(!chinese.matcher(name).matches()){
            throw new BusException("类别名称只能中文");
        }

    }
}